module.exports = {
  tim:null,
  TIM:null,
  config:null,
  init(config,TIM,COS,page){
    let t = this;
    this.TIM = TIM;
    this.config = config;
    let tim = t.tim = TIM.create(config.options);
    tim.setLogLevel(config.setLogLevel);
    // tim.registerPlugin({'cos-wx-sdk': COS});

    // 收到推送的单聊、群聊、群提示、群系统通知的新消息，
    // 可通过遍历 event.data 获取消息列表数据并渲染到页面
    tim.on(TIM.EVENT.MESSAGE_RECEIVED,config.message_received);
    tim.on(TIM.EVENT.ERROR,config.error);
    // tim.on(TIM.EVENT.SDK_READY,function (e) {
    //   t.look(tim,TIM,config);
    // });
    tim.on(TIM.EVENT.SDK_READY,t.sdk_ready,this);
    tim.on(TIM.EVENT.SDK_NOT_READY,t.sdk_no_ready);

    //登录
    tim.login(config.user)
      .then(e=>{
        console.log('登录成功',e);
      })
      .catch(err=>{
        console.log('登录失败:', err);
      });
  },
  sdk_ready(e){
    // 加入群聊
    let t = this;
    console.log('sdk_ready',e,t);
    t.tim.joinGroup(t.config.group)
      .then(res=>{
        switch (res.data.status) {
          case this.TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
            console.log('等待管理员同意',res)
            break;
          case this.TIM.TYPES.JOIN_STATUS_SUCCESS:
            console.log('加群成功',res);
            t.look(t.tim,t.TIM,t.config)
            break;
          default:
            console.log('加群失败',res);
            break;
        }
      })
  },
  sdk_no_ready(e){
    console.log('sdk_no_ready',e);
  },
  look(tim,TIM,config){
    console.log('消息发送')
    let message = tim.createCustomMessage({
      to: config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushLook',
        description: '观看量+1',
        extension: '1'
      }
    });
    tim.sendMessage(message)
      .then(function(imResponse) {
        console.log('消息发送成功',imResponse);
      })
      .catch(function(imError) {
        console.warn('消息发送失败', imError);
      });
  },
  kill(){
    console.log(this);
    this.tim.quitGroup(this.config.group.groupID);
    this.tim.off(this.TIM.EVENT.MESSAGE_RECEIVED,this.config.message_received);
    this.tim.off(this.TIM.EVENT.ERROR,this.config.error);
    this.tim.off(this.TIM.EVENT.SDK_READY,this.sdk_ready);
    this.tim.off(this.TIM.EVENT.SDK_NOT_READY,this.sdk_no_ready);
    this.tim.logout();
  },
}